<script setup lang="ts">
import QrCode from '../components/QrCode.vue'
import { onMounted, ref } from 'vue'
import { getQrCode, checkQrCodeStatus } from '../api/scanLogin'

const useLogin = () => {
  const qrCodeRes = ref<{ dataUrl: string; uuid: string }>()

  const qrCodeStatus = {
    noscan: '使用APP扫码登录',
    scan_wait_confirm: '已扫描，等待确认',
    scan_confirm: '已确认，正在登录',
    scan_cancel: '已取消',
  }

  type QrCodeStatusType = keyof typeof qrCodeStatus
  const qrStatus = ref<string>()

  const getQrCodes = async () => {
    qrCodeRes.value = (await getQrCode()).data

    const status = await checkQrCodeStatus(qrCodeRes.value.uuid)

    qrStatus.value = qrCodeStatus[status.data.status as QrCodeStatusType]

    if (
      status.data.status === 'noscan' ||
      status.data.status === 'scan_wait_confirm'
    ) {
      // 每隔一秒轮询调用检擦二维码状态
      setInterval(() => {
        checkQrCodeStatus(qrCodeRes.value!.uuid).then((res) => {
          qrStatus.value = qrCodeStatus[res.data.status as QrCodeStatusType]
        })
      }, 1000)
    }
  }

  return { getQrCodes, qrCodeRes, qrStatus }
}

const { getQrCodes, qrCodeRes, qrStatus } = useLogin()

onMounted(() => {
  getQrCodes()
})
</script>

<template>
  <div class="code">
    <QrCode :imgUrl="qrCodeRes?.dataUrl" />
    <p>{{ qrStatus }}</p>
    <button @click="getQrCodes">点击刷新</button>
  </div>
</template>

<style scoped>
.code {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -80%);
  text-align: center;
}

button {
  display: inline-block;
  padding: 10px 18px;
  font-size: 13px;
  font-weight: 500;
  line-height: 1.5;
  color: #fff; /* 白色文字 */
  background-color: #1f70ff; /* 稀土掘金主题蓝色 */
  border: none;
  border-radius: 4px;
  width: 150px;
}
</style>
